package CocoFood.servlet;

import javax.servlet.RequestDispatcher;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public abstract class WebServlet extends HttpServlet {

    protected abstract void processRequest(HttpServletRequest request, HttpServletResponse response);

    protected void forward(String url, HttpServletRequest request, HttpServletResponse response) {
        try {
            RequestDispatcher requestDispatcher = request.getRequestDispatcher(url);
            requestDispatcher.forward(request, response);
        } catch (Exception ex) {
            ex.printStackTrace(System.out);
        }
    }

    protected void redirect(String url, HttpServletResponse response) {
        try {
            response.sendRedirect(url);
        } catch (Exception ex) {
            ex.printStackTrace(System.out);
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) {
        try {
            processRequest(request, response);
        } catch (Exception ex) {
            ex.printStackTrace(System.out);
        }
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) {
        try {
            processRequest(request, response);
        } catch (Exception ex) {
            ex.printStackTrace(System.out);
        }
    }

    protected String getCurrentUrl(HttpServletRequest req, boolean withQueryString) {
        String reqUrl = req.getRequestURL().toString();
        String queryString = req.getQueryString();
        if (withQueryString && queryString != null) {
            reqUrl += "?" + queryString;
        }
        return reqUrl;
    }
}